#!/sbin/openrc-run
# Copyright (c) 2015 The OpenRC Authors.
# See the Authors file at the top-level directory of this distribution and
# https://github.com/OpenRC/openrc/blob/master/AUTHORS
#
# This file is part of OpenRC. It is subject to the license terms in
# the LICENSE file found in the top-level directory of this
# distribution and at https://github.com/OpenRC/openrc/blob/master/LICENSE
# This file may not be copied, modified, propagated, or distributed
# except according to the terms contained in the LICENSE file.

description="Delays until the network is online or a specific timeout"

depend()
{
	before *
	need sysfs
	provide network-online
	keyword -jail -prefix -systemd-nspawn
}

get_interfaces()
{
	local ifname iftype
	for ifname in /sys/class/net/*; do
		read iftype < ${ifname}/type
		[ "$iftype" = "1" ] && printf "%s " ${ifname##*/}
	done
}

attempt_with_min_delay() {

	# This function attempts something repeatedly, but if it takes less than one second then
	# it detects this and inserts an artificial 0.5 second "setup delay" so it doesn't blow
	# through all attempts too quickly. Good for when the connectivity test is failing
	# immediately due to DNS resolution error, etc, so makes the connectivity test much easier
	# to write. This connectivity test actually turns out to be a tricky little problem!
	# This should solve it.

	local count=0
	local max_attempts=$1
	local cmd="$2"
	ebegin "Performing connectivity test (attempts=$max_attempts)"
	while [ $count -lt $max_attempts ]; do
		count=$[ $count + 1 ]
		local ts_start=$(date +%s%N)
		eval $cmd
		if [ $? -eq 0 ]; then
			return 0
		fi
		local ts_stop=$(date +%s%N)
		local ts_diff=$[ $ts_stop - $ts_start ]
		if [ $count -lt $max_attempts ] && [ $ts_diff -lt 1000000000 ]; then
			# command took less than 1 sec to run; so wait at least 0.5 seconds between attempts
			sleep 0.5
		fi
	done
	return 1
}

start ()
{
	if [ -n "$connectivity_test" ]; then
		attempt_with_min_delay "${connectivity_attempts:-10}" "$connectivity_test"
		success=$?
		if [ $success -eq 0 ]; then
			eend 0 "The network is now connected"
		else
			# There is not a huge benefit in failing here. Doing so could prevent normal, timely startup.
			# Better to just continue.
			eend 1 "The network failed to connect. Continuing anyway."
		fi
	fi
	return 0
}
